package com.xr.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xr.pojo.Role;
import com.xr.pojo.User;
import com.xr.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    //通过dubbo远程调用服务
    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws
            UsernameNotFoundException {
        User byName = userService.findByName(s);
        if (byName!=null){
            //String username, String password, Collection<? extendsGrantedAuthority> authorities
            String username = byName.getUsername();
            String password = byName.getPassword();
            List<GrantedAuthority> authorities=new ArrayList<>();
            Set<Role> roles = byName.getRoles();
            roles.forEach(role -> {//遍历角色集合,为用户授予角色
                authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                role.getPermissions().forEach(permission -> {//遍历权限集合，为用户授予权限
                    authorities.add(new
                            SimpleGrantedAuthority(permission.getKeyword()));
                });
            });
            //将用户信息返回给框架,框架会进行密码比对（比对页面传递过来的）
            org.springframework.security.core.userdetails.User user=new
                    org.springframework.security.core.userdetails.User(username,password,authorities)
                    ;
            return user;
        }
        return null;
    }

}
